class Solution(object):
    def spiralMatrixIII(self, rows, cols, rStart, cStart):
        out = [[rStart, cStart]]
        index = 1
        n = rows * cols
        now = [rStart, cStart]
        state = 0
        k = 1
        c = 0
        while index < n:
            if state == 0:
                if c < k:
                    now = [now[0], now[1] + 1]
                    if 0 <= now[0] < rows and 0 <= now[1] < cols:
                        out.append(now)
                        index += 1
                    c += 1
                if c == k:
                    state = 1
                    c = 0
            else:
                if state == 1:
                    if c < k:
                        now = [now[0] + 1, now[1]]
                        if 0 <= now[0] < rows and 0 <= now[1] < cols:
                            out.append(now)
                            index += 1
                        c += 1
                    if c == k:
                        state = 2
                        c = 0
                        k += 1
                else:
                    if state == 2:
                        if c < k:
                            now = [now[0], now[1] - 1]
                            if 0 <= now[0] < rows and 0 <= now[1] < cols:
                                out.append(now)
                                index += 1
                            c += 1
                        if c == k:
                            state = 3
                            c = 0
                    else:
                        if c < k:
                            now = [now[0] - 1, now[1]]
                            if 0 <= now[0] < rows and 0 <= now[1] < cols:
                                out.append(now)
                                index += 1
                            c += 1
                        if c == k:
                            state = 0
                            c = 0
                            k += 1
        return out


data = Solution()
rows = 1
cols = 4
rStart = 0
cStart = 0
print(data.spiralMatrixIII(rows, cols, rStart, cStart))
